<?php namespace Framework\Model;

use pdo;

class Db{

	public $table;
	public $sql;

	//为进行链式操作而设置
	public $option=[

		'where'=>'',
		'groupby'=>'',
		'having'=>'',
		'orderby'=>'',
		'limit'=>'',

	];

	public function __construct($table)
	{
		$this->table = $table;
		$this->connect();
	}

	private function connect()
	{
		$dsn = 'mysql:host='.C('db_host').';dbname='.C('db_name');
		// p($dsn);
		$this->pdo = new Pdo($dsn,C('db_user'),C('db_password'));
		$this->pdo->query("set names utf8");
	}

	public function query($sql,$params=[])
	{
		$sth = $this->pdo->prepare($sql);
		$id = 0;
		foreach ($params as $key => $p) {
			$id++;
			$var = 'hd'.$id;
			$$var = $p;
			$sth->bindParam($id,$$var);
		}
		$sth->execute();
		return $sth->fetchALL(PDO::FETCH_ASSOC);
	}

	public function execute($sql,$params=[])
	{
		$sth = $this->pdo->prepare($sql);
		$id = 0;
		foreach ($params as $key => $p) {
			$id++;
			$var = 'hd'.$id;
			$$var = $p;
			$sth->bindParam($id,$$var);
		}
		return $sth->execute();

	}

	//返回INSERT 的主键
	public function getInsertId()
	{
		return $this->pdo->lastInsertId();
	}

	public function select()
	{
		$sql = "SELECT * FROM ".$this->table." {$this->option['where']}{$this->option['groupby']}{$this->option['having']}
			{$this->option['orderby']}{$this->option['limit']}";
			// p($sql);
		return $this->query($sql);
	}

	public function first()
	{
		if($d = $this->select())
		{
			return current($d);
		}
	}


	public function where($arg)
	{
		$this->option['where'] = "WHERE $arg";
		return $this;
	}
		public function groupby($arg)
	{
		$this->option['groupby'] = "GROUPBY $arg";
		return $this;
	}

	public function having($arg)
	{
		$this->option['having'] = "HAVING $arg";
		return $this;
	}

	public function orderby($arg)
	{
		$this->option['orderby'] = "ORDERBY $arg";
		return $this;
	}

	public function limit($arg)
	{
		$this->option['limit'] = "LIMIT $arg";
		return $this;
	}
}